package spring.ioc;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.ioc.bean.TT;
import spring.ioc.bean.User;

import java.util.Map;

/**
 * Spring IoC 依赖查找
 */
public class DependencyLookupDemo {


    public static void main(String[] args) {

        //配置xml,启动spring 应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/dependency-lookup-context.xml");

        lookupByName(beanFactory);
        lookupByType(beanFactory);
        //按类型查找集合对象
        lookupCollectionByType(beanFactory);
        //根据注解查找
        lookupByAnnotionType(beanFactory);

        //实时查找
        lookupInRealTime(beanFactory);
//懒查找
        lookupInLazy(beanFactory);

    }


    private static void lookupByName(BeanFactory beanFactory) {
        User user = (User) beanFactory.getBean("user");
        System.out.println("名称查找："+user.toString());
    }

    private static void lookupByType(BeanFactory beanFactory) {
        User user = beanFactory.getBean(User.class);
        System.out.println("类型查找："+user.toString());
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {

        if (beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
           Map<String ,User> map =  listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查到的所有User集合："+map);
        }
    }

    private static void lookupByAnnotionType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, Object> map =   listableBeanFactory.getBeansWithAnnotation(TT.class);
            System.out.println("Annotion查找："+map);
        }
    }

    private static void lookupInRealTime(BeanFactory beanFactory) {
        User user = (User) beanFactory.getBean("user");
        System.out.println("实时："+user.toString());
    }

    private static void lookupInLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory =(ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User  user = objectFactory.getObject();
        System.out.println("懒："+user.toString());
    }


}
